package com.vviton.zyhj.common.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.Workbook;

public class ExcelUtil {

    /** log **/
    private static Log log = LogFactory.getLog(ExcelUtil.class);

    public static Boolean exportTemplate(HttpServletResponse response, String templateFile, Object data, String fileName) {
        try {
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            OutputStream outStream = new BufferedOutputStream(response.getOutputStream());
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("data", data);
            InputStream inputStream = ExcelUtil.class.getClassLoader().getResourceAsStream(templateFile);
            File outFile = File.createTempFile("temp", "xls");
            byte[] b = saveOutput(map, inputStream, outFile);
            outStream.write(b);
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static byte[] saveOutput(Map<String, Object> data, InputStream templateFile, File outFile) {

        try {
            XLSTransformer transformer = new XLSTransformer();
            Workbook workbook = transformer.transformXLS(templateFile, data);
            //TODO 图片处理

            workbook.write(new FileOutputStream(outFile.getPath()));
            FileInputStream inStream = new FileInputStream(outFile);
            ByteArrayOutputStream outStream = new ByteArrayOutputStream(1000);

            byte[] b = new byte[1000];

            for (int n = 0; (n = inStream.read(b)) != -1;) {
                outStream.write(b, 0, n);
            }
            inStream.close();
            outStream.close();
            return outStream.toByteArray();

        } catch (Exception e) {
            log.error("catch:" + ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

}
